<?php

namespace addons\mental\controller;

use addons\mental\model\WxUser as wxUserModel;
use addons\mental\library\TouTiao;
use fast\Random;
use think\Config;
use think\Session;

class TtUser extends Base
{

    public function login1()
    {
        $code = $this->request->param('code');
        if (empty($code)) {
            $this->error('code', [], 1001);
        }
        //根据code取openid和session_key
        $tou = new TouTiao();
        $result = $tou->codeToSessionkey($code);

        if (!$result['status']) {
            $this->error($result['msg'], $result['data'], 1002);
        }
        $wxUserModel = new wxUserModel();
        $wx_user_id = $wxUserModel->codeToInfo($result, 3);
        Session::set('wx_user_id',$wx_user_id);
        $this->success($result['msg']);
    }


    public function login2()
    {
        $param = $this->request->param();
        $wx_user_id = Session::get('wx_user_id');
        if (empty($wx_user_id)) {
            $this->error('参数错误');
        }
        if (!isset($param['userInfo']) || empty($param['userInfo'])) {
            $this->error(sprintf(__("Parameter %s can not be empty"), 'userInfo'));
        }
        $wxUserModel = new wxUserModel();
        $info = $wxUserModel->where(['id' => $wx_user_id])->find();
        if (!$info) {
            $this->error(__('No results were found'));
        }
        if ($info->user_id != 0) {
            $this->auth->direct($info->user_id);
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        }

        
        //如果未开启手机号码绑定，直接创建账号登录
        if (Config::get('mental.is_bind_mobile') == 1) {
            $username = Random::alnum(20);
            $password = Random::alnum(6);
            $domain = request()->host();
            $ret = $this->auth->register($username, $password, $username . '@' . $domain, '', [
                'nickname' => $param['userInfo']['nickName'],
                'avatar' => $param['userInfo']['avatarUrl']
            ]);
            if (!$ret) {
                $this->error($this->auth->getError());
            }
            $info->user_id = $this->auth->id;
            $wxUserModel->updateTtInfo($param['userInfo'], $info);
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        }

        $status = $wxUserModel->updateTtInfo($param['userInfo'], $info);
        if (!$status) {
            $this->error('登录失败');
        }
        Session::set('wx_user_id', $info['id']);
        $this->success('操作成功！',100);
    }
}
